//
//  GQDistributeStatusController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/12.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQDistributeStatusController.h"
#import "GQDistribuerLocationController.h"
#import "GQDistributeSelecteLabelController.h"
#import "GQHomeController.h"
#import "GQTabBar.h"
#define kStatusMargin 5
#define kVoteHeight 35

@interface GQDistributeStatusController () <UITextViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>

@property (weak, nonatomic) UILabel *wordNumber;
@property (weak, nonatomic) UITextView *textView;
@property (weak, nonatomic) UIImagePickerController *picker;
@property (weak, nonatomic) UIButton *addImageBtn;
@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) UIView *containView;
@property (assign, nonatomic) NSInteger pickerCount;
@property (strong, nonatomic) NSMutableArray *imageArr;
@property (assign, nonatomic) CGRect tempFrame;
@property (assign, nonatomic) int count;
@property (assign, getter=isAnimating, nonatomic) BOOL animating;

@end

@implementation GQDistributeStatusController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"状态";
    self.view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"home_close"] style:UIBarButtonItemStylePlain target:self action:@selector(backToPre)];
    //创建发布按钮
    UIButton *distributeBtnClick = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    distributeBtnClick.titleLabel.font = [UIFont systemFontOfSize:15];
    [distributeBtnClick setTitle:@"发布" forState:UIControlStateNormal];
    [distributeBtnClick setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [distributeBtnClick addTarget:self action:@selector(distributeItemDidClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:distributeBtnClick];
    [self setUpChildView];
    
    NSInteger count = self.images.count;
    for (int i = 0; i < count; i++) {
        [self refreshScrollViewImage:self.images[i]];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyBoardWillHide:(NSNotification *)noti
{
    self.view.transform = CGAffineTransformIdentity;
}

- (void)keyBoardWillShow:(NSNotification *)noti
{
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, -frame.size.height + kNavigatationBarHeight);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)distributeItemDidClick
{
    
}

- (void)backToPre
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)setUpChildView
{
    UIView *containView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigatationBarHeight, self.view.width, 230)];
    [self.view addSubview:containView];
    
    //创建标签提示
    UIButton *labelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    labelBtn.frame = CGRectMake(0, 0, self.view.width, 44);
    [labelBtn addTarget:self action:@selector(labelBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat imageWidth = 29;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"distribute_label"]];
    imageView.frame = CGRectMake(10, (labelBtn.height - imageWidth) / 2, imageWidth, imageWidth);
    [labelBtn addSubview:imageView];
    
    CGFloat tipWidth = 150;
    CGFloat tipHeight = 20;
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 10, (labelBtn.height - tipHeight) / 2, tipWidth, tipHeight)];
    tipLabel.text = @"至少使用一个标签";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = [UIColor colorWithRed:112/255.0 green:215/255.0 blue:208/255.0 alpha:1.0];
    [labelBtn addSubview:tipLabel];
    
    CGFloat advanceWidth = 22;
    UIImageView *advanceView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.width - 10 - advanceWidth, (labelBtn.height - advanceWidth) / 2, advanceWidth, advanceWidth)];
    advanceView.image = [UIImage imageNamed:@"login_arrow"];
    [labelBtn addSubview:advanceView];
    
    //创建分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(labelBtn.frame), containView.width, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    
    //创建text
    CGFloat textHeight = 90;
    UITextView *text = [[UITextView alloc] init];
    text.x = kStatusMargin;
    text.y = CGRectGetMaxY(lineView.frame) + kStatusMargin;
    text.width = containView.width - 2 * kStatusMargin;
    text.height = textHeight;
    text.font = [UIFont systemFontOfSize:14];
    text.delegate = self;
    self.textView = text;
    
    //字数显示
    CGFloat numberHeight = 20;
    UILabel *wordNumber = [[UILabel alloc] init];
    wordNumber.frame = CGRectMake(text.width - 35, text.height - numberHeight, 30, numberHeight);
    wordNumber.font = [UIFont systemFontOfSize:12];
    wordNumber.text = @"120";
    self.wordNumber = wordNumber;
    [text addSubview:wordNumber];
    
    // 创建分割线
    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(text.frame), containView.width, 1)];
    lineView2.backgroundColor = [UIColor lightGrayColor];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lineView2.frame), containView.width, 90)];
    scrollView.contentSize = CGSizeMake(0, 0);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor lightGrayColor];
    self.scrollView = scrollView;
    
    
    //创建图片展示
    UIButton *addImageBtn = [[UIButton alloc] init];
    addImageBtn.x = 10;
    addImageBtn.y = scrollView.x + 5;
    addImageBtn.width = 80;
    addImageBtn.height = 80;
    addImageBtn.layer.borderWidth = 1;
    addImageBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [addImageBtn setBackgroundImage:[UIImage imageNamed:@"distribute_add"] forState:UIControlStateNormal];
    [addImageBtn addTarget:self action:@selector(addImageBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    self.addImageBtn = addImageBtn;
    [self.imageArr addObject:addImageBtn];
    [scrollView addSubview:addImageBtn];
    
    // -------------如果进来是从投票界面进来的----------------
   
    if ([self.type isEqualToString:@"vote"]) {
    
        UILabel *voteLable = [[UILabel alloc] init];
        voteLable.x = 10;
        voteLable.y = CGRectGetMaxY(containView.frame) + 10;
        voteLable.width = 70;
        voteLable.height = 20;
        voteLable.font = [UIFont systemFontOfSize:14];
        voteLable.text = @"投票选项";
        
        //标签
        UITextField *textField1 = [[UITextField alloc] init];
        textField1.x = 0;
        textField1.y = CGRectGetMaxY(voteLable.frame) + 1;
        textField1.width = self.view.width;
        textField1.height = kVoteHeight;
        textField1.placeholder = @"选项一，最多20个字符";
        textField1.textAlignment = NSTextAlignmentCenter;
        textField1.backgroundColor = [UIColor whiteColor];
        textField1.font = [UIFont systemFontOfSize:16];
        textField1.delegate = self;
        
        UITextField *textField2 = [[UITextField alloc] init];
        textField2.x = 0;
        textField2.y = CGRectGetMaxY(textField1.frame) + 1;
        textField2.width = self.view.width;
        textField2.height = kVoteHeight;
        textField2.placeholder = @"选项二，最多20个字符";
        textField2.textAlignment = NSTextAlignmentCenter;
        textField2.backgroundColor = [UIColor whiteColor];
        textField2.font = [UIFont systemFontOfSize:16];
        textField2.delegate = self;
        self.tempFrame = textField2.frame;
        
        UIButton *addOption = [[UIButton alloc] init];
        addOption.x = 0;
        addOption.y = CGRectGetMaxY(textField2.frame) + 1;
        addOption.width = self.view.width;
        addOption.height = kVoteHeight;
        [addOption setTitle:@"+增加一个选项" forState:UIControlStateNormal];
        addOption.titleLabel.font = [UIFont systemFontOfSize:16];
        addOption.backgroundColor = [UIColor whiteColor];
        [addOption addTarget:self action:@selector(addOptionDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [addOption setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.view addSubview:voteLable];
        [self.view addSubview:textField1];
        [self.view addSubview:textField2];
        [self.view addSubview:addOption];
    }
    //-------------------结束-----------------------------
   
    [containView addSubview:labelBtn];
    [containView addSubview:lineView];
    [containView addSubview:text];
    [containView addSubview:lineView2];
    [containView addSubview:scrollView];
    
    self.containView = containView;
    [self.view addSubview:containView];
    
    
    //创建地标位置
    CGFloat locationHeight = 44;
    CGFloat locationLabelHeight = 20;
    UIView *locationView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - locationHeight, self.view.width, locationHeight)];
    [self.view addSubview:locationView];
    
    CGFloat locationImageWidth = 29;
    UIImageView *locationImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"distribute_location"]];
    locationImage.frame = CGRectMake(10, (locationView.height - locationImageWidth) / 2, locationImageWidth, locationImageWidth);
    [locationView addSubview:locationImage];
    locationView.backgroundColor = [UIColor lightGrayColor];
    
    UILabel *locationLabel = [[UILabel alloc] init];
    locationLabel.x = CGRectGetMaxX(locationImage.frame) + 5;
    locationLabel.y = (locationView.height - locationLabelHeight) / 2;
    locationLabel.width = 150;
    locationLabel.height = locationLabelHeight;
    locationLabel.text = @"杭州市白马大厦";
    locationLabel.font = [UIFont systemFontOfSize:15];
    locationLabel.textColor = [UIColor colorWithRed:27/255.0 green:194/255.0 blue:177/255.0 alpha:1.0];
    [locationView addSubview:locationLabel];

    UIView *coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, locationView.width * 0.7, locationView.height)];
    coverView.backgroundColor = [UIColor clearColor];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureDidTap)];
    [coverView addGestureRecognizer:tapGesture];
    [locationView addSubview:coverView];
    
}

#pragma mark - UITextField代理

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - 添加评论按钮
- (void)addOptionDidClick:(UIButton *)btn
{
    if (self.isAnimating) {
        return;
    }
    if (_count == 2) {
        return;
    }
    self.animating = YES;
    NSArray *wordArr = [NSArray arrayWithObjects:@"三", @"四", nil];
    UITextField *textField = [[UITextField alloc] initWithFrame:self.tempFrame];
    textField.y += kVoteHeight + 1;
    textField.x += self.view.width;
    textField.placeholder = [NSString stringWithFormat:@"选项%@，最多20个字符", wordArr[_count]];
    if (_count) {
        [btn setTitle:@"最多四个选项" forState:UIControlStateNormal];
    }
    textField.textAlignment = NSTextAlignmentCenter;
    textField.backgroundColor = [UIColor whiteColor];
    textField.font = [UIFont systemFontOfSize:16];
    textField.delegate = self;
    [self.view addSubview:textField];
    
    [UIView animateWithDuration:0.5 animations:^{
        btn.y = CGRectGetMaxY(self.tempFrame) + kVoteHeight + 2;
        
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            textField.x = 0;
        } completion:^(BOOL finished) {
            self.tempFrame = textField.frame;
            _count++;
            self.animating = NO;
        }];
    }];
    
}

- (void)tapGestureDidTap
{
    GQDistribuerLocationController *GQLC = [[GQDistribuerLocationController alloc] init];
    GQLC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:GQLC animated:NO];
}

#pragma mark - 添加图片按钮
- (void)addImageBtnDidClick
{
    if (self.imageArr.count >= 6) {
        return;
    }
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"相册", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.delegate = self;
        pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerController.allowsEditing = YES;
        [self presentViewController:pickerController animated:YES completion:nil];
        self.picker = pickerController;
    }
}

- (void)labelBtnDidClick
{
    GQDistributeSelecteLabelController *GQDSLC = [[GQDistributeSelecteLabelController alloc] init];
    GQDSLC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:GQDSLC animated:NO];
}



#pragma mark - 刷新UIScrollView
- (void)refreshScrollViewImage:(UIImage *)image
{
    CGFloat addImageMargin = 5;
    
    CGRect currentAddBtnFrame = self.addImageBtn.frame;
    CGFloat addX = self.addImageBtn.x + self.addImageBtn.width + addImageMargin;
    CGFloat addMaxX = addX + self.addImageBtn.width + 10;
    self.scrollView.contentSize = CGSizeMake(addMaxX, 0);
    self.addImageBtn.x = addX;
    if (addMaxX > self.containView.width) {
        self.scrollView.contentOffset = CGPointMake(addMaxX - self.scrollView.width, 0);
    }
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.scrollView addSubview:imageView];
    imageView.alpha = 0;
    imageView.frame = currentAddBtnFrame;
    imageView.layer.borderWidth = 1;
    imageView.userInteractionEnabled = YES;
    imageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    CGFloat cancleWidth = 18;
    UIButton *cancleImageBtn = [[UIButton alloc] init];
    cancleImageBtn.x = imageView.width - cancleWidth;
    cancleImageBtn.y = 0;
    cancleImageBtn.width = cancleWidth;
    cancleImageBtn.height = cancleWidth;

    [cancleImageBtn setImage:[UIImage imageNamed:@"distribute_delete"] forState:UIControlStateNormal];
    [cancleImageBtn addTarget:self action:@selector(cancleBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:cancleImageBtn];
    
    [self.imageArr insertObject:imageView atIndex:self.imageArr.count - 1];
    [UIView animateWithDuration:0.3 delay:0.3 options:0 animations:^{
        imageView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    
}
#pragma mark - 取消按钮事件
- (void)cancleBtnDidClick:(UIButton *)btn
{
    NSInteger index = [self.imageArr indexOfObject:(UIImageView *)btn.superview];
    [btn.superview removeFromSuperview];
    [self.imageArr removeObject:btn.superview];
    NSInteger count = self.imageArr.count;
    for (NSInteger i = index; i < count; i++) {
        UIView *view1 = self.imageArr[i];
        
        [UIView animateWithDuration:0.3 animations:^{
            view1.x -= view1.width + 5;
        }];
    }
    UIView *lastObject = [self.imageArr lastObject];
    CGFloat btnMaxX = CGRectGetMaxX(lastObject.frame) + 10;
    self.scrollView.contentSize = CGSizeMake(btnMaxX, 0);
    if (btnMaxX - self.scrollView.width > 0) {
        self.scrollView.contentOffset =CGPointMake(btnMaxX - self.scrollView.width, 0);
    }else{
        self.scrollView.contentOffset =CGPointMake(0, 0);
    }
    
}
#pragma mark - UIImagePicker的代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self refreshScrollViewImage:image];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 120) {
        self.wordNumber.text = @"0";
        textView.text = [textView.text substringToIndex:120];
    }else{
        NSInteger number = textView.text.length;
        self.wordNumber.text = [NSString stringWithFormat:@"%d", 120 - number];
        
    }
}

#pragma mark - 懒加载
- (NSMutableArray *)imageArr
{
    if (_imageArr == nil) {
        _imageArr = [NSMutableArray array];
    }
    return _imageArr;
}


@end
